package com.sky.service.impl;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;

import com.sky.websocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.weaver.ast.Or;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import static com.sky.constant.MessageConstant.ORDER_NOT_FOUND;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WebSocketServer webSocketServer;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.shop.baidu.ak}")
    private String ak;

    /**
     * 用户下单
     * @param ordersSubmitDTO
     * @return
     */
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //得到一个用户的id
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBook = new AddressBook();
        addressBook.setUserId(userId);

        //判断地址簿中的情况
        List<AddressBook> addressBookList = addressBookMapper.list(addressBook);
        if (addressBookList.size()==0 || addressBookList==null){
            throw new AddressBookBusinessException("地址簿为空了~~");
        }

        addressBook.setIsDefault(1);
        //查询用户默认地址的信息
        List<AddressBook> addressDefault = addressBookMapper.list(addressBook);
        AddressBook address = addressDefault.get(0);

        //检查用户的收货地址是否超出配送范围
        checkOutOfRange(address.getCityName()+address.getDistrictName()+address.getDetail());

        //判断购物车中的情况
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (shoppingCartList.size()==0 || shoppingCartList == null){
            throw new ShoppingCartBusinessException("购物车为空了~~");
        }



        //构造订单数据
        Orders orders = new Orders();
        //属性拷贝
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        //对总金额 进行 四舍五入处理
        BigDecimal amount = orders.getAmount();
        BigDecimal roundedAmount = amount.setScale(2, BigDecimal.ROUND_HALF_UP);
        orders.setAmount(roundedAmount);

        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(address.getPhone());
        orders.setAddress(address.getDetail());
        orders.setConsignee(address.getConsignee());
        orders.setAddressBookId(address.getId());
        //向订单表插入1条数据
        orderMapper.insert(orders);

        //向明细表插入n条数据
        ArrayList<OrderDetail> orderDetailArrayList = new ArrayList<>();
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            orderDetailArrayList.add(orderDetail);
        }
        orderDetailMapper.insertBatch(orderDetailArrayList);

        //清空购物车
        shoppingCartMapper.clearShoppingCart(userId);

        //封装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .orderNumber(orders.getNumber())
                .build();

        return orderSubmitVO;
    }

    /**
     * 订单支付（真实）
     *
     * @param ordersPaymentDTO
     * @return
     */
//    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);
//
//        //调用微信支付接口，生成预支付交易单
//        JSONObject jsonObject = weChatPayUtil.pay(
//                ordersPaymentDTO.getOrderNumber(), //商户订单号
//                new BigDecimal(0.01), //支付金额，单位 元
//                "苍穹外卖订单", //商品描述
//                user.getOpenid() //微信用户的openid
//        );
//
//        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
//            throw new OrderBusinessException("该订单已支付");
//        }
//
//        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
//        vo.setPackageStr(jsonObject.getString("package"));
//
//        return vo;
//    }

    /**
     * 订单支付（模拟）
     */
    public void payment(OrdersPaymentDTO ordersPaymentDTO) throws InterruptedException {

//        Thread.sleep(100);

        paySuccess(ordersPaymentDTO.getOrderNumber());
//        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//
//        //订单号
//        String orderNumber = ordersPaymentDTO.getOrderNumber();
//
//        //根据订单号 订单 信息
//        Orders selectOrders = orderMapper.getByNumberAndUserId(orderNumber, userId);
//
//        //得到该订单 的订单id
//        Long selectId = selectOrders.getId();
//
//        //将订单的状态修改为2
//        Orders orders = new Orders();
//        orders.setId(selectId);
//        orders.setStatus(Orders.TO_BE_CONFIRMED);
//
//        orderMapper.update(orders);

    }


    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo 应该是订单号，以后了去查询一下
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);
    //===========================新添加的代码（未测试）===============================
        // 向浏览器管理端提示来单
        Map map = new HashMap<>();
        map.put("type",1); //消息类型，1表示来单提醒
        map.put("orderId",ordersDB.getId());
        map.put("content","订单号："+outTradeNo);

        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    //==========================================================
    }

    /**
     * 查看历史订单
     * @param page
     * @param pageSize
     * @param status
     * @return
     */
    @Override
    public PageResult getHistoryOrders(Integer page, Integer pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(page, pageSize);

        //把自己活成宝藏
        //设置相应的DTO，进行查询操作
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        //获取到userId
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);
        ordersPageQueryDTO.setStatus(status);

        //进行查询用户所有的订单操作
        Page<Orders> ordersPage = orderMapper.getOrders(ordersPageQueryDTO);

        List<OrderVO> orderVOList = new ArrayList<>();

        //根据查到的订单信息，去查询相应订单的详细信息
        if(ordersPage!=null && ordersPage.size()>0){
            for (Orders order : ordersPage) {
                Long orderId = order.getId();
                //根据 orderId 获取到 相应订单的 详细信息
                List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(orderId);
                OrderVO orderVO = new OrderVO();
                //属性拷贝
                BeanUtils.copyProperties(order,orderVO);
                orderVO.setOrderDetailList(orderDetailList);
                orderVOList.add(orderVO);
            }
        }

        PageResult PageResult = new PageResult(ordersPage.size(),orderVOList);
        return PageResult;
    }

    /**
     * 查询订单详情
     * @param id
     * @return
     */
    @Override
    public OrderVO getOrderDetail(Long id) {
        //根据订单id查询订单信息
        Orders orders = orderMapper.getById(id);
        OrderVO orderVO = new OrderVO();
        //根据订单id查询订单详细信息
        List<OrderDetail> orderDetail = orderDetailMapper.getOrderDetail(id);
        //属性拷贝
        BeanUtils.copyProperties(orders,orderVO);
        orderVO.setOrderDetailList(orderDetail);

        return orderVO;
    }

    /**
     * 取消订单（真实）
     * @param id
     */
//    @Override
//    public void cancelByOrderId(Long id) throws Exception {
//        Orders orders = orderMapper.getById(id);
//        // 如果 Orders 为空
//        if (orders == null){
//            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
//        }
//
//        // 如果Order中的状态有误，我感觉这块相当于是暴力处理了
//        if (orders.getStatus() > 2){
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//        Orders toUpdateOrder = new Orders();
//        toUpdateOrder.setId(id);
//
//        // 如果订单状态是待接单状态下 需要给用户退款
//        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
//            //调用微信支付接口
//            weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
//            //支付状态修改为 退款
//            toUpdateOrder.setPayStatus(Orders.REFUND);
//        }
//
//        //设置 取消原因、取消时间、订单状态
//        toUpdateOrder.setStatus(Orders.CANCELLED);
//        toUpdateOrder.setCancelReason("用户取消");
//        toUpdateOrder.setCancelTime(LocalDateTime.now());
//
//        //更新订单
//        orderMapper.update(toUpdateOrder);
//    }

    /**
     * 取消订单（模拟）
     * @param id
     */
    @Override
    public void cancelByOrderId(Long id) throws Exception {
        Orders orders = orderMapper.getById(id);
        // 如果 Orders 为空
        if (orders == null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }

        // 如果Order中的状态有误，我感觉这块相当于是暴力处理了
        if (orders.getStatus() > 2){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders toUpdateOrder = new Orders();
        toUpdateOrder.setId(id);

        // 如果订单状态是待接单状态下 需要给用户退款
        if(orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
//            //调用微信支付接口
//            weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01));
            //支付状态修改为 退款
            toUpdateOrder.setPayStatus(Orders.REFUND);
        }

        //设置 取消原因、取消时间、订单状态
        toUpdateOrder.setStatus(Orders.CANCELLED);
        toUpdateOrder.setCancelReason("用户取消");
        toUpdateOrder.setCancelTime(LocalDateTime.now());

        //更新订单
        orderMapper.update(toUpdateOrder);
    }

    /**
     * 再来一单
     * @param id
     */
    @Override
    public void repetition(Long id) {
        //得到用户的id
        Long userId = BaseContext.getCurrentId();

        //得到订单的详细数据
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(id);

        //将订单详细数据转换成 购物车数据
        List<ShoppingCart> shoppingCartList = orderDetailList.stream().map(x->{
            ShoppingCart shoppingCart = new ShoppingCart();
            //将原来 订单详情 数据复制到 购物车中
            BeanUtils.copyProperties(x,shoppingCart,"id");
            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());
            return shoppingCart;
        }).collect(Collectors.toList());

        //把 shoppingCartList 添加到购物车中
        shoppingCartMapper.insertBatch(shoppingCartList);

    }

    /**
     * 订单搜索
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult conditionSearch(OrdersPageQueryDTO ordersPageQueryDTO) {
        //设置页面
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());

        //根据 ordersPageQueryDTO 查询出 Orders类型的 Page
        Page<Orders> ordersPage = orderMapper.pageQuery(ordersPageQueryDTO);

        //得到OrderVO类型的List
        List<OrderVO> orderVOList = getOrderVOList(ordersPage);

        return new PageResult(ordersPage.getTotal(),orderVOList);
    }

    /**
     * 返回 List<OrderVO> 结果
     * @param ordersPage
     * @return
     */
    private List<OrderVO> getOrderVOList(Page<Orders> ordersPage) {
        //拿出Orders类型的List
        List<Orders> ordersList = ordersPage.getResult();

        //定义返回
        List<OrderVO> orderVOList = new ArrayList<>();

        //如果 ordersList 不为空
        if(!CollectionUtils.isEmpty(ordersList)){
            //对 ordersList 进行 增强for循环
            for (Orders orders : ordersList) {
                OrderVO orderVO = new OrderVO();
                //属性拷贝
                BeanUtils.copyProperties(orders,orderVO);
                //得到String类型的订单详情
                String orderDishes = getDishStr(orders);
                orderVO.setOrderDishes(orderDishes);
                orderVOList.add(orderVO);
            }
        }

        return orderVOList;
    }

    /**
     * 得到订单的详细信息，并转换成字符串
     * @param orders
     * @return
     */
    private String getDishStr(Orders orders){
        //得到订单的id
        Long orderId = orders.getId();

        //根据订单的id 得到订单的详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetail(orderId);

        //拼接详细订单 菜品 的 名称和数量 返回String类型的List
        List<String> orderDishList =orderDetailList.stream().map(orderDetail->{
                String orderDish = orderDetail.getName() + "*" + orderDetail.getNumber() + ";";
                return orderDish;
            }
        ).collect(Collectors.toList());

        //对 orderDishList 中的值进行再次拼接，得到 一个订单的详细信息
        return String.join("",orderDishList);
    }

    /**
     * 各个状态的订单数量统计
     * @return
     */
    @Override
    public OrderStatisticsVO countStatistics() {
        //待接单
        Integer toBeConfirmed = orderMapper.countStatistics(Orders.TO_BE_CONFIRMED);

        //待派送
        Integer confirmed = orderMapper.countStatistics(Orders.CONFIRMED);

        //派送中
        Integer deliveryInProgress = orderMapper.countStatistics(Orders.DELIVERY_IN_PROGRESS);

        //封装 OrderStatisticsVO
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);

        return orderStatisticsVO;
    }

    /**
     * 接单
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        Orders orders = Orders.builder()
                .id(ordersConfirmDTO.getId())
                .status(Orders.CONFIRMED)
                .build();
        orderMapper.update(orders);
    }

    /**
     * 拒单（真实）
     * @param ordersRejectionDTO
     */
//    @Override
//    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
//        //得到订单的信息
//        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());
//
//        //如果订单不存在 或者 订单的状态 不是 待接单状态 就 抛出异常
//        if(orders==null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
//            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
//        }
//
//        //如果 被拒订单 已付款 需要退款
//        Integer payStatus = orders.getPayStatus();
//        if(payStatus == Orders.PAID){
//           String refund = weChatPayUtil.refund(
//              orders.getNumber(),
//              orders.getNumber(),
//              new BigDecimal(0.01),
//              new BigDecimal(0.01)
//            );
//           log.info("申请退款：{}",refund);
//        }
//
//
//        Orders rejectedOrder = new Orders();
//        rejectedOrder.setId(ordersRejectionDTO.getId());
//        rejectedOrder.setStatus(Orders.CANCELLED);
//        rejectedOrder.setRejectionReason(ordersRejectionDTO.getRejectionReason());
//        rejectedOrder.setCancelTime(LocalDateTime.now());
//
//        //修改订单状态
//        orderMapper.update(rejectedOrder);
//    }

    /**
     * 拒单（模拟）
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) throws Exception {
        //得到订单的信息
        Orders orders = orderMapper.getById(ordersRejectionDTO.getId());

        //如果订单不存在 或者 订单的状态 不是 待接单状态 就 抛出异常
        if(orders==null || !orders.getStatus().equals(Orders.TO_BE_CONFIRMED)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        Orders rejectedOrder = new Orders();
        rejectedOrder.setPayStatus(Orders.REFUND); //支付状态为退款
        rejectedOrder.setId(ordersRejectionDTO.getId());
        rejectedOrder.setStatus(Orders.CANCELLED);
        rejectedOrder.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        rejectedOrder.setCancelTime(LocalDateTime.now());

        //修改订单状态
        orderMapper.update(rejectedOrder);
    }


    /**
     * 取消订单（真实）
     * @param ordersCancelDTO
     */
//    @Override
//    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
//        //得到订单信息
//        Orders orders = orderMapper.getById(ordersCancelDTO.getId());
//
//        //我还有我喜欢的人，我还有有我想要照顾的人，再苦再难我也要坚持，再苦再难我也决不放弃
//        //判断的支付状态订单 如果已经支付了，就退款
//        Integer payStatus = orders.getPayStatus();
//        if(payStatus == Orders.PAID){
//            String refund = weChatPayUtil.refund(
//                    orders.getNumber(),
//                    orders.getNumber(),
//                    new BigDecimal(0.01),
//                    new BigDecimal(0.01)
//            );
//            log.info(refund);
//        }
//
//        //修改订单信息，更改订单
//        Orders canceledOrder = new Orders();
//        canceledOrder.setId(ordersCancelDTO.getId());
//        canceledOrder.setCancelReason(ordersCancelDTO.getCancelReason());
//        canceledOrder.setCancelTime(LocalDateTime.now());
//        canceledOrder.setStatus(Orders.CANCELLED);
//
//        orderMapper.update(canceledOrder);
//    }

    /**
     * 取消订单
     * @param ordersCancelDTO
     */
    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) throws Exception {
        //得到订单信息
        Orders orders = orderMapper.getById(ordersCancelDTO.getId());

        //我还有我喜欢的人，我还有有我想要照顾的人，再苦再难我也要坚持，再苦再难我也决不放弃

        //修改订单信息，更改订单
        Orders canceledOrder = new Orders();
        canceledOrder.setPayStatus(Orders.REFUND); //支付状态为退款
        canceledOrder.setId(ordersCancelDTO.getId());
        canceledOrder.setCancelReason(ordersCancelDTO.getCancelReason());
        canceledOrder.setCancelTime(LocalDateTime.now());
        canceledOrder.setStatus(Orders.CANCELLED);

        orderMapper.update(canceledOrder);
    }

    /**
     * 派送订单
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //得到订单的相关信息
        Orders orders = orderMapper.getById(id);

        //判断订单的状态
        Integer status = orders.getStatus();
        if(orders == null || !status.equals(Orders.CONFIRMED)){
            throw new  OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单  (派送订单)
        Orders deliveryOrder = new Orders();
        deliveryOrder.setId(id);
        //更新订单状态，状态转换为派送中
        deliveryOrder.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(deliveryOrder);
    }


    /**
     * 完成订单
     * @param id
     */
    @Override
    public void complete(Long id) {
        //得到订单
        Orders orders = orderMapper.getById(id);
        //判断订单的状态  只有在订单状态是派送中的订单 才可以 设置成 完成订单 状态
        Integer status = orders.getStatus();
        if(orders==null || !status.equals(Orders.DELIVERY_IN_PROGRESS)){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        //修改订单状态为 已完成
        Orders completedOrder = new Orders();
        completedOrder.setId(id);
        completedOrder.setStatus(Orders.COMPLETED);
        completedOrder.setDeliveryTime(LocalDateTime.now());

        orderMapper.update(completedOrder);
    }

    /**
     * 检查客户的收货地址是否超出配送范围
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);

        //获取店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;

        map.put("address",address);
        //获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        map.put("origin",shopLngLat);
        map.put("destination",userLngLat);
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");
        }
    }


    /**
     * 催单
     * @param id
     */
    @Override
    public void reminder(Long id) {
        //根据 id查询 得到 订单信息
        Orders order = orderMapper.getById(id);

        //人这一辈子 很快就过去了，所以说 好好珍惜吧。
        //判断 order 是否为空
        if (order == null){
            throw new OrderBusinessException(ORDER_NOT_FOUND);
        }

        //通过 WebSocket 向 浏览器管理端 催单
        Map map = new HashMap<>();
        map.put("type",2);
        map.put("orderId",order.getId());
        map.put("content","订单号："+order.getNumber());

        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }
}
